package com.sukaiyi.leetcode._1195fizz_buzz_multithreaded;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.IntConsumer;

/**
 * @author sukaiyi
 * @date 2020/06/24
 */
public class FizzBuzz {

    private int n;

    private final Object lock = new Object();

    private volatile AtomicInteger current = new AtomicInteger(1);

    public FizzBuzz(int n) {
        this.n = n;
    }

    // printFizz.run() outputs "fizz".
    public void fizz(Runnable printFizz) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            if (i % 3 == 0 && i % 5 != 0) {
                while (current.get() != i) {
                    Thread.yield();
                }
                printFizz.run();
                current.incrementAndGet();
            }
        }
    }

    // printBuzz.run() outputs "buzz".
    public void buzz(Runnable printBuzz) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            if (i % 5 == 0 && i % 3 != 0) {
                while (current.get() != i) {
                    Thread.yield();
                }
                printBuzz.run();
                current.incrementAndGet();
            }
        }
    }

    // printFizzBuzz.run() outputs "fizzbuzz".
    public void fizzbuzz(Runnable printFizzBuzz) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            if (i % 5 == 0 && i % 3 == 0) {
                while (current.get() != i) {
                    Thread.yield();
                }
                printFizzBuzz.run();
                current.incrementAndGet();
            }
        }
    }

    // printNumber.accept(x) outputs "x", where x is an integer.
    public void number(IntConsumer printNumber) throws InterruptedException {
        for (int i = 1; i <= n; i++) {
            if (i % 5 != 0 && i % 3 != 0) {
                while (current.get() != i) {
                    Thread.yield();
                }
                printNumber.accept(i);
                current.incrementAndGet();
            }
        }
    }
}
